<template>
    <div class="min-h-screen flex flex-col">
        <!-- Header -->
        <header class="header bg-white p-4 shadow-md flex justify-between items-center">

            <div class="container flex items-center">
                <div class="links-container"> <!-- 新增的容器 -->
                    <a href="#" class="flex items-center text-gray-600 hover:text-blue-500">
                        <i class="icon-download"></i>
                        <span class="ml-1">下载App</span>
                    </a>
                    <a href="#" class="text-blue-500 font-bold hover:underline">栏目收费说明</a>
                </div>
                <!-- 使用 v-if/v-else 来条件渲染登录/注册按钮或用户信息 -->
                <div v-if="!username" class="lrcs items-center space-x-4"> <!-- Flex 布局让内容一行排列 -->
                    <RouterLink class="btn-login" :to="{ name: 'Login', query: { redirecturl: router.currentRoute.value.fullPath } }">登录</RouterLink>
                    <RouterLink class="btn-register" to='/register'>注册</RouterLink>
                </div>
                <div v-else class="user-info flex items-center space-x-3"> <!-- 用户信息 -->
                    <img :src="avatar" alt="用户头像" class="user-avatar w-8 h-8 rounded-full" />
                    <span>{{ username }}</span>
                    <span class="text-logout" @click="logout">退出</span>
                </div>

            </div>
        </header>

        <!-- Search -->
        <div class="search-header">
            <div class="search-wrapper">
                <h1 class="text-a">丁香医生</h1>
                <input type="text" v-model="searchQuery" placeholder="搜索疾病、医院、药品" class="search-input" />
                <button class="search-button">搜索</button>
            </div>
        </div>

        <!-- Navigation -->
        <nav class="main-nav">
            <router-link v-for="item in navigationItems" :key="item.name" :to="item.link" class="nav-link">
                {{ item.name }}
            </router-link>
        </nav>

        <!-- Breadcrumb Navigation -->
        <div class="breadcrumb-container mb-4">
            <nav class="flex items-center text-sm">
                <router-link to="/" class="text-emerald-500 hover:text-emerald-600">首页</router-link>
                <span class="mx-2 text-gray-400">›</span>
                <router-link to="/disease" class="text-emerald-500 hover:text-emerald-600">查疾病</router-link>
                <span class="mx-2 text-gray-400">›</span>
                <span class="text-gray-700" v-if="selectedDepartment">{{ selectedDepartment.name }}</span>
            </nav>

            <!-- 分类 -->
            <div class="qa-container">
                <div class="content-wrapper">
                    <div class="categories-container">
                        <div class="category-box">
                            <div class="category-header">科室</div>
                            <div class="category-content">
                                <button v-for="dept in departments" :key="dept.id" @click="selectDepartment(dept)"
                                    :class="['category-btn', selectedDepartment?.id === dept.id ? 'active' : '']">
                                    {{ dept.name }}
                                </button>
                            </div>
                        </div>

                        <div class="category-box">
                            <div class="category-header">常见疾病</div>
                            <div class="category-content">
                                <button v-for="treatment in treatments" :key="treatment.id"
                                    @click="navigateToDisease(treatment.id)"
                                    :class="['category-btn', selectedTreatment?.id === treatment.id ? 'active' : '']">
                                    {{ treatment.name }}
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- 疾病列表 -->
                    <div class="main-content-area">
                        <div class="disease-list-box">

                            <div class="disease-list-item" v-for="disease in treatments" :key="disease.id"
                                @click="navigateToDisease(disease.id)">
                                <h4 class="disease-item-title">{{ disease.name }}</h4>
                                <p class="disease-item-content" v-html="disease.remark.slice(0,30)+'...'"></p>
                            </div>
                        </div>

                        <!-- 医生侧边界面 -->
                        <div class="sidebar-box department-doctors">
                            <h3>相关科室医生</h3>
                            <div class="doctor-card" @click="navigateToDoctor(doctor.id)"
                                v-for="doctor in departmentDoctors" :key="doctor.id">
                                <img :src="doctor.avatar" alt="Doctor" class="doctor-avatar" />
                                <div class="doctor-info">
                                    <div class="doctor-name">{{ doctor.name }}</div>
                                    <div class="doctor-title-dept">
                                        {{ doctor.get_title_display }} {{ doctor.department }}
                                    </div>
                                    <div class="doctor-hospital">{{ doctor.hospital }}</div>
                                    <div class="doctor-stats">
                                        <span class="doctor-price">¥{{ doctor.consultation_price }}</span>
                                        <span class="doctor-rating">{{ doctor.rating }}分</span>
                                        <span class="doctor-consults">{{ doctor.consultation_count }}问答</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>


            <!-- Footer -->
            <footer class="mt-auto">
                <div class="bottom-links">
                    <a target="_blank" href="http://www.dxy.cn/pages/copyright.html" rel="nofollow">版权声明</a>
                    <a target="_blank" href="https://dxy.com/column/board" rel="nofollow">作者编委</a>
                    <a target="_blank" href="https://ask.dxy.com/ama/index" rel="nofollow">丁香医生</a>
                    <a href="mailto:doctor@dxy.com" rel="nofollow">投稿邮箱 doctor@dxy.com</a>
                    <a target="_blank">客服电话：0571-22931767</a>
                </div>
            </footer>
        </div>
    </div>




</template>


<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { jwtDecode } from 'jwt-decode';

const router = useRouter();
const username = ref < string | null > (null);
const avatar = ref < string | null > (null);
const searchQuery = ref('');
const navigationItems = [
    { name: '问医生', link: '/sections' },
    { name: '查疾病', link: '/disease' },
    { name: '查药品', link: '/medicine' },
    { name: '查医院', link: '/hospital' },
    { name: '查检查/手术', link: '/examination' },
    { name: '查疫苗', link: '/vaccine' },
    { name: '急救指南', link: '/emergency' },
    { name: '测一测', link: '/test' },
    { name: '科普视频', link: '/videos' }
];

interface Department {
    id: number;
    name: string;
}

interface Treatment {
    id: number;
    name: string;
    department: string;
    remark: string;
    
}




interface Doctor {
    id: number;
    name: string;
    avatar: string;
    get_title_display: string;
    hospital: string;
    department: string;
    price: number;
    rating: number;
    consult_count: number;
}

const departments = ref < Department[] > ([]);
const treatments = ref < Treatment[] > ([]);
const departmentDoctors = ref < Doctor[] > ([]);
const selectedDepartment = ref < Department | null > (null);
const selectedTreatment = ref < Treatment | null > (null);

// 登录
// const fetchUserInfo = async () => {
//     const token = localStorage.getItem('token');
//     if (token) {
//         const payload = JSON.parse(atob(token.split('.')[1]));
//         const userId = payload.id;

//         const response = await fetch(`http://127.0.0.1:8000/user/userinfo/${userId}/`, {
//             headers: { 'Authorization': `Bearer ${token}` }
//         });
//         const data = await response.json();
//         username.value = data.username;
//         avatar.value = data.avatar;
//     }
// };

const fetchUserInfo = async () => {
    const token = localStorage.getItem('token');
    if (token) {
        const payload = ref<any>(jwtDecode(token));
        username.value = payload.value.username;
        avatar.value = 'http://127.0.0.1:8000/uploads/' + payload.value.avatar;
        console.log(avatar.value);
    }

}

const logout = () => {
    localStorage.removeItem('token');
    username.value = null;
    avatar.value = null;
};

// 获取科室
const fetchDepartments = async () => {
    try {
        const response = await axios.get('http://127.0.0.1:8000/doctor/department/0/');
        departments.value = response.data;
        if (departments.value.length > 0) {
            selectDepartment(departments.value[0]);
        }
    } catch (error) {
        console.error('Error fetching departments:', error);
    }
};

const selectDepartment = async (department: Department) => {
    selectedDepartment.value = department;
    selectedTreatment.value = null;
    await Promise.all([
        fetchTreatments(department.id),
        
        fetchDepartmentDoctors(department.id)
    ]);
};

// 获取疾病
const fetchTreatments = async (departmentId: number) => {
    try {
        const response = await axios.get(`http://127.0.0.1:8000/doctor/treat/${departmentId}/`);
        treatments.value = response.data;
    } catch (error) {
        console.error('Error fetching treatments:', error);
    }
};




// 获取医生
const fetchDepartmentDoctors = async (departmentId: number) => {
    try {
        const response = await axios.get(`http://127.0.0.1:8000/doctor/doctor/${departmentId}/`);
        departmentDoctors.value = response.data.slice(0, 3);
    } catch (error) {
        console.error('Error fetching department doctors:', error);
    }
};

const navigateToDisease = (treatId: number) => {
    // router.push(`/treat/${treatId}`);
    window.open(`/treat/${treatId}` , '_blank');
};

const navigateToDoctor = (doctorId: number) => {
    // router.push(`/doctor/${doctorId}`);
    window.open(`/doctor/${doctorId}` , '_blank');
};

onMounted(() => {
    fetchDepartments();
    fetchUserInfo();
    fetchTreatments(1);
});


</script>

<style scoped>
/* 登录注册 */
/* Header Styling */
.header {
    background-color: #ffffff;
    /* White background */
    color: #333333;
    /* Gray text color */
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    /* Subtle shadow */
    padding: 16px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

/* Left Content Links */
.header a {
    text-decoration: none;
    color: #666666;
    font-size: 14px;
    display: flex;
    align-items: center;
    transition: color 0.3s ease;
}

.header a:hover {
    color: #00b38a;
    /* Match green color on hover */
}

.header a.text-blue-500 {
    color: #00b38a;
    /* Green color for special links */
    font-weight: bold;
    margin-left: 16px;
}

.text-logout {
    margin-left: 16px;
    background-color: transparent;
    /* 透明背景 */
    border: none;
    /* 无边框 */
    color: #666666;
    /* 文本颜色与下载链接一致 */
    padding: 0;
    /* 移除内边距 */
    font-size: 14px;
    font-weight: normal;
    /* 正常字体粗细 */
    cursor: pointer;
    text-decoration: none;
    /* 移除下划线 */
    transition: color 0.3s ease;
    /* 颜色过渡效果 */
}

.text-logout:hover {
    color: #00b38a;
    text-decoration: underline;

}


.container {
    display: flex;
    align-items: center;

    flex-wrap: nowrap;

    gap: 16px;
    margin-right: 350px;

}

/* 可以添加一个包含栏目、下载等链接的容器样式 */
.links-container {
    display: flex;
    align-items: center;
    /* 之间的间隔 */



}



/* Right Content Buttons */

.btn-login {
    background-color: transparent;
    /* 透明背景 */
    border: none;
    /* 无边框 */
    color: #666666;
    /* 文本颜色与下载链接一致 */
    padding: 0;
    /* 移除内边距 */
    font-size: 14px;
    font-weight: normal;
    /* 正常字体粗细 */
    cursor: pointer;
    text-decoration: none;
    /* 移除下划线 */
    transition: color 0.3s ease;
    /* 颜色过渡效果 */
}

.btn-register {
    background-color: transparent;
    /* 透明背景 */
    border: none;
    /* 无边框 */
    color: #666666;
    /* 文本颜色与下载链接一致 */
    padding: 0;
    /* 移除内边距 */
    font-size: 14px;
    font-weight: normal;
    /* 正常字体粗细 */
    cursor: pointer;
    text-decoration: none;
    /* 移除下划线 */
    transition: color 0.3s ease;
    /* 颜色过渡效果 */
    margin-left: 13px;
}

.lrcs {
    display: flex;
    align-items: center;

}

/* 添加伪类来模仿下载链接的hover效果 */
.btn-login:hover,
.btn-register:hover {
    color: #00b38a;
    /* 悬停时变为绿色 */
    text-decoration: underline;
    /* 悬停时添加下划线 */
}

/* User Info Styling */
.user-info {
    display: flex;
    align-items: center;
}

.user-info .user-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    /* Circular avatar */
    object-fit: cover;

}

.user-info span {
    font-size: 14px;
    font-weight: 500;
    color: #333333;
}

/* 搜索 */
.search-header {
    background-color: #fff;
    padding: 20px 0;
}

.search-wrapper {
    max-width: 600px;
    margin: 0 auto;
    display: flex;
    gap: 10px;
}

.text-a {
    font-size: 32px;
    font-weight: 700;
    color: #00b38a;
    margin: 0 auto;
    letter-spacing: 1px;
}

.search-input {
    flex: 1;
    padding: 12px 20px;
    border: 2px solid #00b38a;
    border-radius: 24px;
    font-size: 16px;
    outline: none;
}
.search-button {
    padding: 12px 30px;
    background-color: #00b38a;
    color: white;
    border: none;
    border-radius: 24px;
    cursor: pointer;
    font-size: 16px;
}

/* 顶部导航 */
.main-nav {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10px 0;
    background-color: #fff;
    border-bottom: 1px solid #eee;
}

.nav-link {
    padding: 6px 16px;
    color: #666;
    text-decoration: none;
    font-size: 14px;
    transition: color 0.2s;
}

.nav-link:hover {
    color: #00b38a;
}

/* 面包屑导航 */
.breadcrumb-container {
    max-width: 1000px;
    margin: 0 auto;
}

.breadcrumb-container nav .text-emerald-500 {
    transition: color 0.3s ease;
}

.breadcrumb-container nav .text-emerald-500:hover {
    color: #00b38a;
}

/* 底部 */
.bottom-links {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 8px;
    padding: 24px;
    background-color: #f5f5f5;
}

.bottom-links a {
    color: #666;
    text-decoration: none;
    padding: 4px 8px;
}

.bottom-links a:hover {
    color: #00b38a;
}

/* 分类 */
.qa-container {
    background-color: #f8f9fa;
    min-height: 100vh;
    padding: 24px 0;
}

.content-wrapper {
    max-width: 1000px;
    margin: 0 auto;
    padding: 0 20px;
}

.categories-container {
    margin-bottom: 32px;
}

.category-box {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    margin-bottom: 16px;
    padding: 20px;
}

.category-header {
    color: #333;
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #eee;
}

.category-content {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
}

.category-btn {
    padding: 6px 16px;
    background-color: #f5f5f5;
    border: none;
    border-radius: 4px;
    color: #666;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.2s ease;
    white-space: nowrap;
}

.category-btn:hover {
    background-color: #e6f7f4;
    color: #00b38a;
}

.category-btn.active {
    background-color: #00b38a;
    color: white;
}

/* 侧边栏医生 */
.sidebar-box {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 24px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.sidebar-box h3 {
    font-size: 18px;
    font-weight: 500;
    color: #333;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #eee;
}

.doctor-card {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    cursor: pointer;
    padding: 12px;
    border-radius: 8px;
    transition: background-color 0.2s;
}

.doctor-card:hover {
    background-color: #f5f5f5;
}

.doctor-avatar {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    object-fit: cover;
}

.doctor-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.doctor-name {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    line-height: 1.2;
}

.doctor-title-dept {
    font-size: 14px;
    color: #666;
    line-height: 1.2;
}

.doctor-hospital {
    font-size: 14px;
    color: #666;
    line-height: 1.2;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.doctor-stats {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-top: 2px;
}

.doctor-price {
    color: #00b38a;
    font-size: 14px;
    font-weight: 500;
}

.doctor-rating,
.doctor-consults {
    color: #666;
    font-size: 14px;
}

/* 疾病列表 */
.disease-list-box {
    flex: 1;
}

.disease-list-title {
    font-size: 18px;
    font-weight: 500;
    color: #333;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #eee;
}

.disease-list-item {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 16px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    cursor: pointer;
    transition: box-shadow 0.3s ease;

}

.disease-list-item:hover {
    box-shadow: 0 1px 6px rgba(0, 0, 0, 0.2);

 }

.disease-item-title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
}

.disease-item-content {
    font-size: 14px;
    color: #666;
    margin-top: 4px;
}


.main-content-area {
    display: flex;
    gap: 24px;
    margin-top: 24px;
}
</style>